package o2o.config.memcached;

import com.danga.MemCached.MemCachedClient;
import com.jinyou.utils.common.DateUtils;
import com.jinyou.utils.common.ValidateUtil;
import o2o.cache.user.UserOnlineImpl;
import o2o.config.init.AutoWiredClass;
import o2o.web.actions.system.token.KeyValueBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * 类名称：MemcacheUtil
 * 类描述：  获取memcached客户端
 * 创建人：Jahnke 1029777564@qq.com
 * 创建时间：2016年8月13日 下午4:02:18
 * 修改备注：
 */
@Service
public class MemcacheUtil {

    private static MemcacheUtil memcacheUtil = new MemcacheUtil();

    @Autowired
    private MemCachedClient client;

    private static MemCachedClient client2;

    @PostConstruct
    public void init() {
        client2 = client;
    }

    private synchronized MemCachedClient getMemCachedClient() {
        return AutoWiredClass.client2;
    }

    private MemcacheUtil() {
    }

    /**
     * 获取唯一实例.
     *
     * @return
     */
    public static MemcacheUtil getInstance() {
        if (memcacheUtil == null) {
            synchronized (MemcacheUtil.class) {
                memcacheUtil = new MemcacheUtil();
            }
        }
        return memcacheUtil;
    }

    public boolean add(String key, Object value) {
        return getMemCachedClient().add(key, value);
    }

    public boolean add(String key, Object value, Integer expire) {
        return getMemCachedClient().add(key, value, expire);
    }

    public boolean put(String key, Object value) {
        return getMemCachedClient().set(key, value);
    }

    public boolean put(String key, Object value, Integer expire) {
        return getMemCachedClient().set(key, value, expire);
    }

    public boolean replace(String key, Object value) {
        return getMemCachedClient().replace(key, value);
    }

    public boolean replace(String key, Object value, Integer expire) {
        return getMemCachedClient().replace(key, value, expire);
    }

    //清空所有的缓存信息
    public boolean flushAll() {
        return getMemCachedClient().flushAll();
    }

    //判断key是否存在
    public boolean keyExit(String key) {
        return getMemCachedClient().keyExists(key);
    }

    //删除一个key值
    public boolean delete(String key) {
        return getMemCachedClient().delete(key);
    }

    public Object get(String key) {
        return getMemCachedClient().get(key);
    }

    public Map<String, String> getKeysForMap() {
        Map<String, String> keylist = new HashMap<String, String>();
        //遍历statsItems 获取items:2:number=14
        Map<String, Map<String, String>> statsItems = getMemCachedClient().statsItems();
        Map<String, String> statsItems_sub = null;
        String statsItems_sub_key = null;
        int items_number = 0;
        String server = null;
        //根据items:2:number=14，调用statsCacheDump，获取每个item中的key
        Map<String, Map<String, String>> statsCacheDump = null;
        Map<String, String> statsCacheDump_sub = null;
        String statsCacheDumpsub_key = null;
        String statsCacheDumpsub_key_value = null;

        for (Iterator iterator = statsItems.keySet().iterator(); iterator.hasNext(); ) {
            server = (String) iterator.next();
            statsItems_sub = statsItems.get(server);
            //System.out.println(server+"==="+statsItems_sub);
            for (Iterator iterator_item = statsItems_sub.keySet().iterator(); iterator_item.hasNext(); ) {
                statsItems_sub_key = (String) iterator_item.next();

                System.out.println(statsItems_sub_key);
                //System.out.println(statsItems_sub_key+":=:"+bb);
                //items:2:number=14
                if (statsItems_sub_key.toUpperCase().startsWith("items:".toUpperCase()) && statsItems_sub_key.toUpperCase().endsWith(":number".toUpperCase())) {
                    items_number = Integer.parseInt(statsItems_sub.get(statsItems_sub_key).trim());
                    //System.out.println(statsItems_sub_key+":=:"+items_number);
                    statsCacheDump = getMemCachedClient().statsCacheDump(new String[]{server}, Integer.parseInt(statsItems_sub_key.split(":")[1].trim()), items_number);

                    for (Iterator statsCacheDump_iterator = statsCacheDump.keySet().iterator(); statsCacheDump_iterator.hasNext(); ) {
                        statsCacheDump_sub = statsCacheDump.get(statsCacheDump_iterator.next());
                        //System.out.println(statsCacheDump_sub);
                        for (Iterator iterator_keys = statsCacheDump_sub.keySet().iterator(); iterator_keys.hasNext(); ) {
                            statsCacheDumpsub_key = (String) iterator_keys.next();
                            if (ValidateUtil.isNotNull(statsCacheDumpsub_key)) {

                            }
//                            statsCacheDumpsub_key_value = statsCacheDump_sub.get(statsCacheDumpsub_key);
                            //System.out.println(statsCacheDumpsub_key);//key是中文被编码了,是客户端在set之前编码的，服务端中文key存的是密文
                            //System.out.println(statsCacheDumpsub_key_value);

//                            System.out.println(statsCacheDumpsub_key_value.substring(statsCacheDumpsub_key_value.indexOf("b;") + 2, statsCacheDumpsub_key_value.indexOf("s]") - 1).trim());
//                            keylist.put(statsCacheDumpsub_key, new MemcacheKeysBean(server, Long.parseLong(statsCacheDumpsub_key_value.substring(1, statsCacheDumpsub_key_value.indexOf("b;") - 1).trim()), Long.parseLong(statsCacheDumpsub_key_value.substring(statsCacheDumpsub_key_value.indexOf("b;") + 2, statsCacheDumpsub_key_value.indexOf("s]") - 1).trim())));
                            keylist.put(statsCacheDumpsub_key, statsCacheDumpsub_key_value);
                        }
                    }
                }

            }
        }
        return keylist;
    }


    // 删除用户缓存的token
    public static void removeByUsername(String username) {
        if (ValidateUtil.isNull(username)) {
            return;
        }
        MemCachedClient memCachedClient = getInstance().getMemCachedClient();
        if (null == memCachedClient) {
            return;
        }
        List<String> list = new ArrayList<String>();
        Map<String, Map<String, String>> items = memCachedClient.statsItems();
        if (null == items) {
            return;
        }
        for (Iterator<String> itemIt = items.keySet().iterator(); itemIt.hasNext(); ) {
            String itemKey = itemIt.next();
            Map<String, String> maps = items.get(itemKey);
            for (Iterator<String> mapsIt = maps.keySet().iterator(); mapsIt.hasNext(); ) {
                String mapsKey = mapsIt.next();
                if (ValidateUtil.isNull(mapsKey)) {
                    continue;
                }
                String mapsValue = maps.get(mapsKey);
                if (ValidateUtil.isNull(mapsValue)) {
                    continue;
                }
                if (mapsKey.endsWith("number")) {  //memcached key 类型  item_str:integer:number_str
                    String[] arr = mapsKey.split(":");
                    if (null == arr || arr.length < 1) {
                        continue;
                    }
                    int slabNumber = Integer.valueOf(arr[1].trim());
                    int limit = Integer.valueOf(mapsValue.trim());
                    Map<String, Map<String, String>> dumpMaps = memCachedClient.statsCacheDump(slabNumber, limit);
                    for (Iterator<String> dumpIt = dumpMaps.keySet().iterator(); dumpIt.hasNext(); ) {
                        String dumpKey = dumpIt.next();
                        Map<String, String> allMap = dumpMaps.get(dumpKey);
                        if (null == allMap) {
                            continue;
                        }
                        for (Iterator<String> allIt = allMap.keySet().iterator(); allIt.hasNext(); ) {
                            String allKey = allIt.next();
                            String keyUsername = UserOnlineImpl.getInstance().getByMemKey(allKey.trim());
                            if (ValidateUtil.isNotNull(keyUsername) && keyUsername.equalsIgnoreCase(username)) {
                                // 删除
                                getInstance().delete(allKey);
                                System.out.println(DateUtils.getCurrentDateTime() + " 删除token：" + allKey + ":" + keyUsername + "-" + username);
                            }
                            list.add(allKey.trim());
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取服务器上面所有的key
     *
     * @return
     * @author liu787427876@126.com
     * @date 2013-12-4 MemCachedClient memCachedClient
     */
    public static List<KeyValueBean> getAllKeysBean() {
        MemCachedClient memCachedClient = getInstance().getMemCachedClient();
        List<KeyValueBean> list = new ArrayList<>();
        Map<String, Map<String, String>> items = memCachedClient.statsItems();
        for (Iterator<String> itemIt = items.keySet().iterator(); itemIt.hasNext(); ) {
            String itemKey = itemIt.next();
            Map<String, String> maps = items.get(itemKey);
            for (Iterator<String> mapsIt = maps.keySet().iterator(); mapsIt.hasNext(); ) {
                String mapsKey = mapsIt.next();
                String mapsValue = maps.get(mapsKey);
                if (mapsKey.endsWith("number")) {  //memcached key 类型  item_str:integer:number_str
                    String[] arr = mapsKey.split(":");
                    int slabNumber = Integer.valueOf(arr[1].trim());
                    int limit = Integer.valueOf(mapsValue.trim());
                    Map<String, Map<String, String>> dumpMaps = memCachedClient.statsCacheDump(slabNumber, limit);
                    for (Iterator<String> dumpIt = dumpMaps.keySet().iterator(); dumpIt.hasNext(); ) {
                        String dumpKey = dumpIt.next();
                        Map<String, String> allMap = dumpMaps.get(dumpKey);
                        for (Iterator<String> allIt = allMap.keySet().iterator(); allIt.hasNext(); ) {
                            String allKey = allIt.next();
                            String username = UserOnlineImpl.getInstance().getByMemKey(allKey.trim());

                            KeyValueBean keyValueBean = new KeyValueBean();
                            keyValueBean.setKey(allKey);
                            keyValueBean.setValue(username);
//                            System.out.println(allKey + ":" + username);
                            list.add(keyValueBean);
                        }
                    }
                }
            }
        }
        return list;
    }


}
